// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;

namespace RealWorld.Grids
{
    public class GroupingGridView : GridView
    {
        protected Table InnerTable
        {
            get
            {
                if (false == this.HasControls())
                    return null;

                return (Table)this.Controls[0];
            }
        }

        public int GroupingDepth
        {
            get
            {
                object val = this.ViewState["GroupingDepth"];
                if (null == val)
                {
                    return 0;
                }

                return (int)val;
            }
            set
            {
                if (value < 0)
                    throw new ArgumentOutOfRangeException("value", "value must be greater than or equal to zero");

                this.ViewState["GroupingDepth"] = value;
            }
        }

        protected override void OnDataBound(EventArgs e)
        {
            base.OnDataBound(e);

            this.SpanCellsRecursive(0, 0, this.Rows.Count);
        }

        private void SpanCellsRecursive(int columnIndex, int startRowIndex, int endRowIndex)
        {
            if (columnIndex >= this.GroupingDepth || columnIndex >= this.Columns.Count )
                return;

            TableCell groupStartCell = null;
            int groupStartRowIndex = startRowIndex;

            for (int i = startRowIndex; i < endRowIndex; i++)
            {
                TableCell currentCell = this.Rows[i].Cells[columnIndex];

                bool isNewGroup = (null == groupStartCell) || (0 != String.CompareOrdinal(currentCell.Text, groupStartCell.Text));
                
                if (isNewGroup)
                {
                    if (null != groupStartCell)
                    {
                        SpanCellsRecursive(columnIndex + 1, groupStartRowIndex, i);
                    }

                    groupStartCell = currentCell;
                    groupStartCell.RowSpan = 1;
                    groupStartRowIndex = i;
                }
                else
                {
                    currentCell.Visible = false;
                    groupStartCell.RowSpan += 1;
                }
            }

            SpanCellsRecursive(columnIndex + 1, groupStartRowIndex, endRowIndex);
        }
    }
}
